import React, { Component } from 'react';
import {
	TouchableOpacity, StyleSheet, Text, View, Image, DeviceEventEmitter, FlatList, ActivityIndicator, PixelRatio
} from "react-native";
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import ToastUtil from '../../../utils/toast';
import { GLOBAL } from '../../../config/global';
import { style } from '../../../theme/style';
import { PageStatusIndex } from '../../../component/page-status/PageStatusIndex';
import { Common } from '../../../component/common/Common.js';
import ModalDoubleComponent from '../../../component/ModalDoubleComponent.js';
import Dictionary from '../../../utils/dictionary';

const scale = GLOBAL.SCALE;

let pageNo = 1;//当前第几页
let totalPage = 1;//总的页数
let recordCount = 0;//总的数量

const requestObj = {
	pageNo: 1,
	pageSize: 10,
	status: '',
	month: '',
};
const echartIcon = require('../../../imgs/global/echart.png');
let sendData = {
	onrefresh: false,
	pageNo: 1,
	dictKey: '',
	product: '',
};

export class RequirementPlanPage extends Component {
	static navigationOptions = ({ navigation, navigationOptions }) => {
		return {
			headerTitle: '客户需求计划',
			headerLeft: <Common type="headLeft" onPress={() => { navigation.goBack() }} />,
			headerTintColor: style.color.dark,
			headerStyle: style.headTow.headerStyleWidthBorder,
			headerTitleStyle: style.headTow.headerTitleStyle,
		}
	};

	constructor(props) {
		super(props);
		this.state = {
			pageStatus: {
				status: 'loading'
			},
			loaded: true,
			emptyResult: false,
			dataSource: [],
			showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中		
			corpResult: [],
			modalVisible: false, //  部门顶部下拉
			goodsModal: false,// 商品数据
			goodsValue: '请选择',
			goodsListVal: [],
			goodsList: [],
			companyData: [],
		}
		this._fetchStockInfo = this._fetchStockInfo.bind(this);
		this._renderItem = this._renderItem.bind(this);
		this.headData = [
			{ title: '全部', page: '0' }
		];
		this.headIndex = 0;
		this.department = '全部状态';//部门条件
		this.productIndex = 0;
		this.product = '计划月份';
	}

	async _fetchStockInfo (pageNo) {
		const { companyData } = this.state;
		requestObj.pageNo = pageNo;
		if (this.headIndex != '0') {
			requestObj.status = companyData[this.headIndex * 1 - 1]['dictKey'];;
		} else {
			requestObj.status = '';
		}

		requestObj.month = sendData.product;
		const responseData = await HTTP.POST(API_GENERATE(API.DAMAND_LIST), requestObj);
		if (!responseData) {

			this.setState({
				loaded: false,
				dataSource: [],
			});

		} else {
			const { rows } = responseData;
			recordCount = responseData.recordCount;
			totalPage = responseData.totalPage;

			let foot = 0;
			if (pageNo >= totalPage) {
				foot = 1;//listView底部显示没有更多数据了
			}
			this.setState({
				dataSource: this.state.dataSource.concat(rows),
				// dataSource: responseData,
				loaded: false,
				showFoot: foot
			});
		}
	}

	async componentWillMount () {
		sendData.dictKey = '';
		sendData.product = '';
		this.setState({
			goodsModal: false,// 商品数据
			goodsValue: '请选择',
			goodsListVal: [],
			goodsList: [],
		});
		this._getCompanyData();//公司列表
		this._getGoodsList();
		await this._fetchStockInfo(pageNo);

		let dict = await Dictionary.get('EC_AUDIT_STATUS');
		this.setState({
			corpResult: dict
		})

		this.emitter = DeviceEventEmitter.addListener('requirementListener', async () => {
			console.log('requirementListener');
			pageNo = 1;
			totalPage = 1;//总的页数
			recordCount = 0;//总的数量
			this.setState({
				dataSource: [],
				loaded: true,
			});
			await this._fetchStockInfo(pageNo);
		});
	}

	//获取商品 - 数据APPRO_PRICE_BATCH1/GET_GOODSLIST
	async _getGoodsList () {
		var data = [];
		var date = new Date;
		var year = date.getFullYear();
		for (var i = 3; i > 0; i--) {
			data[data.length] = year * 1 - i;
		}
		data[data.length] = year;
		for (var i = 1; i < 2; i++) {
			data[data.length] = year * 1 + i;
		}
		let responseData = [];
		for (var i = 0; i < data.length; i++) {
			var year1 = data[i] + "";
			var monthData = this._getDataList(year1);
			responseData[i] = { text: year1 + "年", val: year1, dataSource: monthData };
		}
		/*let responseData = [{
			text: "2018年", val: "2018", dataSource: [{ parentId: '2018', text: "1月", val: "201801" },
			{ parentId: '2018', text: "2月", val: "201802" },
			{ parentId: '2018', text: "3月", val: "201803" },
			{ parentId: '2018', text: "4月", val: "201804" },
			{ parentId: '2018', text: "5月", val: "201805" },
			{ parentId: '2018', text: "6月", val: "201806" },
			{ parentId: '2018', text: "7月", val: "201807" },
			{ parentId: '2018', text: "8月", val: "201808" },
			{ parentId: '2018', text: "9月", val: "201809" },
			{ parentId: '2018', text: "10月", val: "201810" },
			{ parentId: '2018', text: "11月", val: "201811" },
			{ parentId: '2018', text: "12月", val: "201812" }]
		}];*/
		console.log('responseData', responseData);
		this.setState({
			goodsList: responseData
		})
	}

	_getDataList (year) {
		var data = [];
		for (var i = 1; i <= 12; i++) {
			var month = i + '月';
			var monthVal = year + (i < 10 ? '0' + i : i);
			data[i - 1] = { parentId: year, text: month, val: monthVal }
		}
		return data;
	}

	async _getCompanyData () {
		let companyData = await HTTP.POST(API_GENERATE(API.GET_DATA_DICTIONARY), {
			dictTypeCode: 'EC_PLAN_APPLY_STATUS'
		});
		if (!companyData) return;
		this.setState({
			companyData: companyData
		})
		var data = [];
		data[0] = { title: '全部', page: '0' };
		companyData.forEach((item, i) => {
			var dictName = item['dictName'];
			data[(i * 1 + 1)] = { title: dictName, page: (i * 1 + 1) };
		});
		this.headData = data;
	}

	_selecGoods = (obj, index) => {
		console.log(obj, '007')
		var onTe = true;

		for (key in obj) {
			obj[key] = true;
			if (key == 'settlementPriceModal' || key == 'reasectPriceModal') {
				if (!sendData.goodsId) {
					onTe = false;
					ToastUtil.showWarning('请先选择商品');
				}
			}
		}
		if (onTe) {
			this.setState(obj);
		}

	}

	_showVisible = () => {
		if (this.state.modalVisible) {
			this.setState({
				modalVisible: false
			})
		} else {
			this.setState({
				modalVisible: true
			})
		}
	}
	_itemFn = (sendObj) => {
		const { companyData } = this.state;
		this._showVisible();
		this.headIndex = sendObj.page;
		this.department = this.headData[sendObj.page]['title'];
		//this.state.status = 'loading';
		sendData.dictKey = sendObj.page == 0 ? '' : companyData[sendObj.page - 1]['dictKey'];

		//this._getListData();
		this.setState({
			loaded: true,
			dataSource: [],
		});
		this._fetchStockInfo(1);
		//if (!sendObj.page) return;
		//this.props.navigation.navigate(sendObj.page);
	}

	_modal = () => {
		return (
			/* 头部弹框 */
			<Common itemFn={this._itemFn} data={this.headData} imgIndex={this.headIndex} allClick={this._showVisible} type="selectModal" />
		)
	}

	/* ---选择产品--- */
	//选计划月份  关闭按钮
	_cancelPress = () => {
		this.setState({ goodsModal: false })
	}
	//选计划月份  确定按钮
	_confirmPress = (data) => {
		if (data.length > 0) {
			this.setState({
				goodsModal: false,
				goodsValue: data[0].text,
			}, function () {
				sendData.product = data[0].val;
				this.productIndex = data[0].val;
				this.product = data[0].val;
				this.setState({
					loaded: true,
					dataSource: [],
				});
				this._fetchStockInfo(1);
				//this._getListData();
				//sendData.goodsId = data[0].goodsId;
				//sendData.goodsName = data[0].goodsName;
				//this._getPriceData();  //长约才有  暂时不用
				//this._settlementPriceData()
			})
		} else {
			this.setState({
				goodsModal: false,
			})
		}
	}

	render () {
		const { pageStatus, goodsModal, goodsList, goodsListVal } = this.state;
		const renderDataView = this.renderData();
		let downImg = require('../../../imgs/global/down.png');//下拉图标
		return (
			<View style={styles.container}>
				<View style={styles.conditionView}>
					<TouchableOpacity style={{ flexDirection: 'row', marginLeft: 57 * scale, }} onPress={this._showVisible.bind(this)}>
						<Text>{this.department}</Text>
						<Image source={downImg} style={{ marginTop: 8 * scale, width: 7 * scale, height: 4 * scale, marginLeft: 11 * scale }}></Image>
					</TouchableOpacity>
					<TouchableOpacity style={{ flexDirection: 'row', marginRight: 57 * scale }} onPress={() => { this._selecGoods({ goodsModal }) }}>
						<Text numberOfLines={1} ellipsizeMode='tail'>{this.product}</Text>
						<Image source={downImg} style={{ marginTop: 8 * scale, width: 7 * scale, height: 4 * scale, marginLeft: 11 * scale }}></Image>
					</TouchableOpacity>
				</View>
				{renderDataView}
				{this.state.modalVisible ? this._modal() : null}
				{goodsList.length > 0 ? (<ModalDoubleComponent
					modalVisible={goodsModal}
					dataSource={goodsList}
					title='选择计划日期'
					selectVals={goodsListVal}
					single={1}
					cancelPress={this._cancelPress}
					confirmPress={this._confirmPress}
				/>) : null}
				<View style={styles.submitBtnCell}>
					<TouchableOpacity activeOpacity={0.5} style={styles.submitBtn}
						onPress={() => { this.props.navigation.navigate('RequirementAdd') }} >
						<Text style={styles.submitBtnText}>添加</Text>
					</TouchableOpacity>
				</View>
			</View >
		)
	}

	renderData () {
		const { loaded, dataSource } = this.state;
		//(dataSource.length);
		if (loaded) {
			return (
				<PageStatusIndex status={'loading'} />);
		} else {
			if (dataSource.length) {
				return (
					<FlatList
						data={this.state.dataSource}
						renderItem={this._renderItem}
						ListFooterComponent={this._renderFooter.bind(this)}
						onEndReachedThreshold={1}
						onEndReached={this._onEndReached.bind(this)}
						onRefresh={this._onRefresh.bind(this)}
						refreshing={false}
					/>
				);
			} else {
				return (
					<PageStatusIndex status={'empty'} title={'text'} />);
			}
		}
	}

	_renderItem (demand) {
		const { status, createTime, companyName, goodsName, quantity, demandId, deliveryMethod,
			staffName, suggestQuantity, auditRemark, statusName, month } = demand.item;
		const suggestQuantityText = (status == 'PASS') ? <Text style={styles.text} numberOfLines={1}>经营计划部建议量：{suggestQuantity || '无'}</Text> : null;
		return (

			<TouchableOpacity key={demand.index} activeOpacity={0.5} style={styles.demand} onPress={() => {
				this.props.navigation.navigate('RequirementDetilPage', {
					demandId
				});
			}} >
				<View style={styles.demandHead}>
					<Text style={styles.text}>{companyName}</Text>
					<Text style={styles.statusText}> {statusName}</Text>
				</View>
				<View style={{ flex: 1, flexDirection: 'row', }}>
					<View style={styles.demandCol}>
						<View style={styles.demandRow}>
							<Text style={styles.text}>业务员：{staffName}</Text>
						</View>
						<View style={styles.demandRow}>
							<Text style={styles.text}>数量：{quantity}</Text>
						</View>
						<View style={styles.demandRow}>
							<Text style={styles.text}>提交时间：{this._getDateStr(createTime)}</Text>
						</View>
					</View>
					<View style={styles.demandCol}>
						<View style={styles.demandRow}>
							<Text style={styles.text}>商品名称：{goodsName}</Text>
						</View>
						<View style={styles.demandRow}>
							<Text style={styles.text}>计划月份：{month}</Text>
						</View>
						<View style={styles.demandRow}>
							<Text style={styles.text}>交货方式：{deliveryMethod}</Text>
						</View>
						{/* <View style={styles.demandRow}>
							{suggestQuantityText}
						</View> */}
						{
							status === 'PASS' ?
								<View style={styles.demandRow}>
									<Text style={styles.text} numberOfLines={1}>经营计划部建议量：{suggestQuantity || '无'}</Text>
								</View> : null
						}
						{
							status === 'UNPASS' ?
								<View style={styles.demandRow}>
									<Text style={styles.text}>驳回原因：{auditRemark || '无'}</Text>
								</View> : null
						}
					</View>

				</View>
			</TouchableOpacity >
		)
	}

	_getDateStr (str) {
		if (str && str.length) {
			const currDate = (typeof str == 'string') ? new Date(str.replace(/-/g, '/')) : str;

			var y = currDate.getFullYear(),
				m = currDate.getMonth() + 1,
				d = currDate.getDate();
			var dateStr = "";
			dateStr += y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
			return dateStr;
		} else {
			return '';
		}
	}

	/*下拉*/
	_onRefresh () {
		this.setState({
			dataSource: [],
			loaded: true,
		});
		pageNo = 1;
		requestObj.pageNo = pageNo;
		this._fetchStockInfo(pageNo);
	}

	/*上拉*/
	_onEndReached () {
		//如果是正在加载中或没有更多数据了，则返回
		if (this.state.showFoot != 0) {
			return;
		}
		//如果当前页大于或等于总页数，那就是到最后一页了，返回
		if ((pageNo != 1) && (pageNo >= totalPage)) {
			return;
		} else {
			pageNo++;
		}
		//底部显示正在加载更多数据
		this.setState({ showFoot: 2 });
		//获取数据
		this._fetchStockInfo(pageNo);
	}

	/*for FlatList的底部*/
	_renderFooter () {
		if (this.state.showFoot === 1) {
			const text = (pageNo > 1) ? '没有更多数据了' : null;
			return (
				<View style={{ height: 30, alignItems: 'center', justifyContent: 'flex-start', }}>
					<Text style={styles.noMoreText}>{text}</Text>
				</View>
			);
		} else if (this.state.showFoot === 2) {
			return (
				<View style={styles.footer}>
					<ActivityIndicator />
					<Text>正在加载更多数据...</Text>
				</View>
			);
		} else if (this.state.showFoot === 0) {
			const curRecordCount = pageNo * requestObj.pageSize;
			return (
				<PageStatusIndex status="bottom" recordCount={recordCount} nowList={curRecordCount} />
			);
		}
	}

}

const styles = StyleSheet.create({
	statusText: {
		fontSize: 14 * scale,
		color: style.color.themeColor,
	},
	container: {
		flex: 1,
		backgroundColor: '#f5f5f5',
	},
	text: {
		fontSize: 12 * scale,
		color: '#4B4B4B'
	},
	demand: {
		backgroundColor: '#fff',
		marginTop: 12 * scale,
		height: 144 * scale,
	},
	demandHead: {
		flexDirection: 'row',
		height: 42 * scale,
		width: 375 * scale,
		justifyContent: 'space-between',
		alignItems: 'center',
		borderBottomColor: '#e4e4e4',
		borderBottomWidth: 1 / PixelRatio.get(),
		paddingLeft: 12 * scale,
		paddingRight: 12 * scale,
	},
	demandCol: {
		flex: 1,
	},
	demandRow: {
		flex: 1,
		justifyContent: 'center',
		paddingLeft: 14 * scale,
	},
	footer: {
		flexDirection: 'row',
		height: 24,
		justifyContent: 'center',
		alignItems: 'center',
		marginBottom: 10,
	},
	noMoreText: {
		color: '#999999',
		fontSize: 14 * scale,
		marginTop: 5 * scale,
		marginBottom: 5 * scale,
	},
	priceListCont: {
		paddingTop: 15 * scale,
		backgroundColor: '#F6F6F6'
	},
	priceListItemCont: {
		paddingTop: 10 * scale,
		paddingBottom: 10 * scale,
		borderBottomWidth: 1 / PixelRatio.get(),
		borderStyle: 'solid',
		borderBottomColor: style.color.border,
		backgroundColor: '#fff'
	},
	priceListItem: {
		flexDirection: 'row',
		alignItems: 'center',
		height: 30 * scale,
		paddingLeft: 15 * scale,
		paddingRight: 15 * scale,
	},
	priceListItemValue: {
		flex: 1,
		fontSize: 13 * scale,
		color: style.color.normal,
	},
	submitBtnCell: {
		height: 60,
		width: '100%',
		justifyContent: 'center',
		alignItems: 'center',
	},
	submitBtn: {
		justifyContent: 'center',
		alignItems: 'center',
		width: 345 * scale,
		height: 44 * scale,
		borderRadius: 100,
		backgroundColor: style.color.themeColor,
	},
	submitBtnText: {
		color: '#fff',
		fontSize: 18 * scale,
	}, conditionView: {
		flexDirection: 'row',
		height: 40 * scale,
		backgroundColor: '#FFFFFF',
		justifyContent: 'space-between',
		alignItems: 'center',
	},
})